package com.example.curator.lock;

import com.example.curator.CuratorClientUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 分布式锁测试
 *
 * @author majie
 * @date 2018/6/29.
 */
public class DistributionLockDemo {

    public static void main(String[] args) {
        Random random = new Random();
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CountDownLatch countDownLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executorService.execute(( ) -> {
                CuratorFramework curatorFramework = CuratorClientUtils.getInstance();
                InterProcessMutex interProcessMutex = new InterProcessMutex(curatorFramework, "/lock");
                try {
                    countDownLatch.countDown();
                    countDownLatch.await();
                    interProcessMutex.acquire();
                    System.out.println("获取成功" + finalI);
                    Thread.sleep(random.nextInt(500));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        System.out.println("释放成功" + finalI);
                        interProcessMutex.release();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        executorService.shutdown();
    }
}
